package com.unohacha.qqj.fzdr.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.BaseRVAdapter;
import com.unohacha.qqj.fzdr.adapter.BaseViewHolder;
import com.unohacha.qqj.fzdr.adapter.NineGridViewClickAdapter2;
import com.unohacha.qqj.fzdr.bean.homebean.HomeAppSellerAreaBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeSellerAreaListBean;
import com.unohacha.qqj.fzdr.imp.MyApplication;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.main.sends.SendNoteActivity;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.mylibrary.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 商家讨论区 item_seller_area item_find_pic
 */
public class SellerAreaActivity extends BaseActivity implements OnRefreshLoadmoreListener {

    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.pt_tabs)
    TabLayout mTabLayout;
    @BindView(R.id.pt_line)
    ImageView ptLine;
    @BindView(R.id.car_list_recycler)
    RecyclerView carListRecycler;
    @BindView(R.id.mRefreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.title_ll)
    LinearLayout titleLl;
    @BindView(R.id.common_cancle)
    ImageView commonCancle;
    @BindView(R.id.edt_seach)
    EditText edtSeach;
    @BindView(R.id.common_right_search)
    TextView commonRightSearch;
    @BindView(R.id.search_ll)
    LinearLayout searchLl;
    @BindView(R.id.send_iv)
    ImageView sendIv;

    private List<String> mFragmentsTitle = new ArrayList<String>();//碎片的标题
    private int page = 1;
    private int app_cate_id = 52;//商家讨论区id 52
    private List<HomeAppSellerAreaBean.DataBean> mDataList = new ArrayList<>();
    private List<HomeSellerAreaListBean.DataBeanX.DataBean> mAreaList = new ArrayList<>();
    private BaseRVAdapter mBaseAdapter;
    private List<HomeAppSellerAreaBean.DataBean> titleList;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_seller_area;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setText(getResources().getString(R.string.sj_area));
        commonRightText.setVisibility(View.GONE);
        commonRightImage.setVisibility(View.VISIBLE);
        commonRightImage.setImageResource(R.drawable.ic_search_black);

        initRefreshLayout();
        getSellerAreaData(52);
    }

    private void initRefreshLayout() {
        mRefreshLayout.setOnRefreshLoadmoreListener(this);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(this));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(this));
        carListRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
    }

    //初始化tab
    private void initTabLayout(List<String> mFragmentsTitle0) {

        for (int i = 0; i < mFragmentsTitle0.size(); i++) {
            mTabLayout.addTab(mTabLayout.newTab().setText(mFragmentsTitle.get(i)), i);
        }
        app_cate_id = mDataList.get(0).getId();
        getAreaList("");
        mTabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.black));
        mTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                app_cate_id = mDataList.get(tab.getPosition()).getId();
                page = 1;
                getAreaList("");
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    //商家讨论区分类标题
    private void getSellerAreaData(int id){
        Map<String,Object> params = new HashMap<>();
        params.put("id",id);
        XUtil.Post(UrlConfig.APP_CATE_LIST,params,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("TAG:　getSellerAreaData",result.toString());
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (1 == jsonObject.optInt("code")){
                        Gson gson = new Gson();
                        HomeAppSellerAreaBean areaBean = gson.fromJson(result,HomeAppSellerAreaBean.class);
                        titleList = areaBean.getData();
                        if (null != areaBean){
                            if (null != mDataList){
                                mDataList.clear();
                            }
                            mDataList.addAll(areaBean.getData());
                            for (int i = 0; i < mDataList.size(); i++) {
                                mFragmentsTitle.add(i,mDataList.get(i).getName());
                            }
                            initTabLayout(mFragmentsTitle);
                        }
                    }else if (100 == jsonObject.optInt("code")){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        MyToast(jsonObject.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }
    
    private void getAreaList(String keyword){
        showLoading();
        Map<String,Object> params = new HashMap<>();
        params.put("app_cate_id",app_cate_id);
        params.put("keyword",keyword);
        params.put("address_id", Prefer.obtainReLocation(this));
        params.put("page",page);
        XUtil.Post(UrlConfig.APP_BUSINESS_LIST,params,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("TAG: getAreaList," ,result.toString());
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (1 == jsonObject.optInt("code")){
                        Gson gson = new Gson();
                        HomeSellerAreaListBean listBean = gson.fromJson(result,HomeSellerAreaListBean.class);
                        if (null != listBean){
                            if (page == 1){
                                if (null != mAreaList){
                                    mAreaList.clear();
                                }

                                mAreaList.addAll(listBean.getData().getData());
                                mRefreshLayout.finishRefresh();
                                mRefreshLayout.resetNoMoreData();
                            }else {
                                mRefreshLayout.finishLoadmore();
                                mBaseAdapter.notifyDataSetChanged();
                            }
                            setAreaListAdapter();
                        }
                    }else if (100 == jsonObject.optInt("code")){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        if (page == 1){
                            MyToast(jsonObject.optString("message"));
                            if (null != mAreaList){
                                mAreaList.clear();
                            }
                            
                            mRefreshLayout.finishRefresh();
                            mRefreshLayout.resetNoMoreData();
                            mBaseAdapter.notifyDataSetChanged();
                        }else {
                            MyToast(getResources().getString(R.string.no_more_data));
                            mRefreshLayout.finishLoadmore();
                            mRefreshLayout.finishLoadmoreWithNoMoreData();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                hideLoading();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                hideLoading();
            }
        });
    }
    
    private void setAreaListAdapter(){
        mBaseAdapter = new BaseRVAdapter(this,mAreaList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_seller_area;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                final int tagPosition = position;
                ImageView store_logo_iv = holder.getImageView(R.id.store_logo_iv);
                TextView store_name_tv = holder.getTextView(R.id.store_name_tv);
                TextView store_report_title = holder.getTextView(R.id.store_report_title);
                TextView content_send = holder.getTextView(R.id.content_send);
                TextView report_time_tv = holder.getTextView(R.id.report_time_tv);
                TextView comment_num = holder.getTextView(R.id.comment_num);
                
                if (0 != mAreaList.size()){
                    Glide.with(SellerAreaActivity.this).load(mAreaList.get(position).
                            getMember_thumb()).error(R.drawable.ic_default_photo).into(store_logo_iv);
                    store_name_tv.setText(mAreaList.get(position).getMember_no());
                    store_report_title.setText(mAreaList.get(position).getTitle());
                    content_send.setText(mAreaList.get(position).getContent());
                    report_time_tv.setText(mAreaList.get(position).getCreate_time());
                    comment_num.setText("评论: " + mAreaList.get(position).getCommon_nums());


                    //九宫格展示
                    ArrayList<ImageInfo> imageInfo = new ArrayList<>();
                    List<String> imageDetails = mAreaList.get(position).getList_pic_compress();
                    if (imageDetails != null) {
                        for (String imageDetail : imageDetails) {
                            ImageInfo info = new ImageInfo();
                            info.setThumbnailUrl(imageDetail);
                            info.setBigImageUrl(imageDetail);
                            imageInfo.add(info);
                        }
                    }

                    NineGridView mRecyclerView = holder.getView(R.id.mRecyclerView);//图片的列表 3 列
                    if (!TextUtils.isEmpty(mAreaList.get(position).getWidth()) && !TextUtils.isEmpty(mAreaList.get(position).getHeight())) {
                        float wh = Float.valueOf(mAreaList.get(position).getWidth())
                                /Float.valueOf(mAreaList.get(position).getHeight());
                        mRecyclerView.setSingleImageRatio(wh);
                    }else {
                        mRecyclerView.setSingleImageSize(500); 
                    }
                    mRecyclerView.setAdapter(new NineGridViewClickAdapter2(mContext, imageInfo));

                }
            }
        };
        mBaseAdapter.addItemClickListener(new BaseRVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                Intent intent = new Intent(SellerAreaActivity.this,TalkDetailActivity2.class);
                intent.putExtra("supply_id",mAreaList.get(position).getId());
                intent.putExtra("data",mAreaList.get(position));
                startActivity(intent);
            }
        });
        carListRecycler.setAdapter(mBaseAdapter);
    }
    
    @OnClick({R.id.common_back,R.id.common_right_image,
             R.id.common_cancle,R.id.common_right_search,R.id.send_iv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                finish();
                break;

            case R.id.common_right_image://搜索
                searchLl.setVisibility(View.VISIBLE);
                edtSeach.setText("");
                titleLl.setVisibility(View.GONE);
                break;
            case R.id.common_cancle://取消
                searchLl.setVisibility(View.GONE);
                titleLl.setVisibility(View.VISIBLE);
                edtSeach.setText("");
                break;
            case R.id.common_right_search://搜索按钮
                if (!TextUtils.isEmpty(edtSeach.getText().toString().trim())) {
                    page = 1;
                    getAreaList(edtSeach.getText().toString().trim());
                }else {
                   MyToast("请输入搜索内容!");
                   return;
                }
                break;
            case R.id.send_iv://发布
                Intent intent = new Intent(SellerAreaActivity.this, SendNoteActivity.class);
                intent.putExtra("titleList",(Serializable) titleList);
                startActivity(intent);
                break;
        }
    }


    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page++;
                getAreaList("");
            }
        }, 2000);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 1;
                getAreaList("");
            }
        }, 2000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
